package com.sdcqjy.mylibrary.http;

import android.os.Handler;
import android.os.Looper;

import com.sdcqjy.mylibrary.Logger;

/**
 * Created by 磁磁帅 on 2017/10/15.
 * 功能：
 */
public abstract class BaseRequestBack<T> implements HttpClient.RequestBack {
    private Handler handler;
    private T t;
    private int retType;
    private String retStr;

    public BaseRequestBack() {
        handler = new Handler(Looper.getMainLooper());
    }

    public void onResponse(int retType, String retStr) throws Exception {
        this.retType = retType;
        this.retStr = retStr;
        if (retType == HttpClient.HttpOnResponse) t = jsonToMode(retStr);
        handler.post(runnable);
    }

    public abstract T jsonToMode(String jsonStr);

    public abstract void onResponseSucc(T ret);//成功

    public abstract void onResponseFail(String retStr);//失败

    public void onResponseCance(String retStr) {//取消
    }

    public Runnable runnable = new Runnable() {
        public void run() {
            if (retType == HttpClient.HttpOnResponse) {
                try {
                    onResponseSucc(t);
                } catch (Exception e) {
                    if (Logger.isDebug) e.printStackTrace();
                    onResponseFail(null);
                }
            } else if (retType == HttpClient.HttpOnFailure) {
                onResponseFail(retStr);
            } else if (retType == HttpClient.HttpOnCanceled) {
                onResponseCance(retStr);
            }
        }
    };
}
